package com.sm.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import com.sm.controller.request.UpdatePasswordRequest;
import com.sm.controller.request.UserLoginRequest;
import com.sm.entity.User;
import com.sm.service.UserService;
import com.sm.utils.R;
import com.sm.utils.RD;
import com.sm.utils.SaTokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @author Cola
 * @description
 * @date 2022/2/4
 */
@RestController
public class UserController {

    @Resource
    UserService userService;

    /**
     * @author cola
     * @description 用户登录（学生、老师、管理员）
     * @date 2022/2/4
     */
    @RequestMapping("/user/login")
    RD login(@RequestBody @Valid UserLoginRequest userLoginRequest) throws Exception {
        userService.login(userLoginRequest);
        String token = StpUtil.getTokenValue();
             return RD.success().putData("token",token);
    }

    /**
     * @author cola
     * @description 用户修改密码（学生和老师）
     * @date 2022/2/4
     */
    @PostMapping("/user/update/password")
    @SaCheckRole(value = {"student","teacher"},mode = SaMode.OR)
    R updatePassword(@RequestBody UpdatePasswordRequest updatePasswordRequest) throws Exception {
        userService.updatePassword(updatePasswordRequest);
        return R.success();
    }

    /**
    * @author cola
    * @description 返回个人信息
    * @date 2022/3/3
    */
    @GetMapping("/user/info")
    RD getInfo() throws Exception {
        List<String> roles = StpUtil.getRoleList();
        User user = userService.getUser();
        String userId = String.valueOf(SaTokenUtils.getUserId());
        String username = user.getUsername();
        String address = user.getAddress();
        String name = user.getRealName();
        String phone = user.getPhone();
        String gender = user.getGender();
        return RD.success().putData("roles",roles).
                putData("name",name).
                putData("username",username).
                putData("address",address).
                putData("phone",phone).
                putData("gender",gender).
                putData("id",userId);
    }


}
